<?php

namespace app\common\model;

use app\common\lib\exception\ApiException;
use app\common\lib\Orders as OrdersLib;
use app\common\lib\Util;
use app\everyday\controller\Index as FortuneIndex;
use app\everyday\controller\Index;
use Exception;
use think\Cache;
use app\common\lib\astrolog\Astrolog;
use think\Env;
use think\response\Json;

/**
 * 日运 缓存类
 * Class DivinationTips
 * @package app\common\model
 */
class FortuneCache extends Base
{

    /**
     * 缓存时长（单位 s）
     */
    const CACHE_TIME = 86400;

    /**
     * 今日天象（与时间有关，与用户无关，每天变化）【string】
     */
    const REDIS_KEY_ASTRO_TIP = 'd_f_h_astro_tips';

    /**
     * 星象变动名字（写死的，不区分rid和time）
     */
    const REDIS_KEY_ASTRO_CHANGE_NAME = 'd_f_astro_change_name';
    /**
     * 星象变动图标（写死的，不区分rid和time）
     */
    const REDIS_KEY_ASTRO_CHANGE_ICON_URL = 'd_f_astro_change_icon_url';

    /**
     *  困难、警戒、平平、吉利、大吉 name和color（因为是写死的，不需要区分key）
     */
    const REDIS_KEY_GRAPH_ICON_URL = 'd_f_graph';

    /**
     * 首页 宜【多个】【存原始数据】
     */
    const REDIS_KEY_HOME_SUITABLE = 'd_f_h_suitable_';

    /**
     * 详情页 宜【多个】【存原始数据】
     */
    const REDIS_KEY_DETAIL_SUITABLE = 'd_f_d_suitable_';

    /**
     * 首页 忌【多个】【存原始数据】
     */
    const REDIS_KEY_HOME_AVOID = 'd_f_h_avoid_';

    /**
     * 首页 忌【多个】【存原始数据】
     */
    const REDIS_KEY_DETAIL_AVOID = 'd_f_d_avoid_';

    /**
     * 幸运元素 【四个】【存转换数据】
     */
    const REDIS_KEY_SYMBOLS = 'd_f_symbols_';

    /**
     * 柱状图【9个】【存原始数据】
     */
    const REDIS_KEY_GRAPHS = 'd_f_graphs_';

    /**
     * **之日【多个】【存转换数据】
     */
    const REDIS_KEY_DAYS = 'd_f_days_';

    /**
     * 各项指南【多个】【存转换数据】
     */
    const REDIS_KEY_ADVICES = 'd_f_advices_';

    /**
     * 女神赠言【1个】【存转换数据】
     */
    const REDIS_KEY_TIPS = 'd_f_tips_';


    /**
     * 首页 **之日【一个】
     */
    const REDIS_KEY_HOME_DAY = 'd_f_h_day_';
    /**
     * 首页 太阳落座（用户属于什么星座）
     */
    const REDIS_KEY_HOME_SUN_IN_SIGN = 'd_f_h_sun_in_sign_';

    /**
     * 详情页 所有的数据，除了不变的和宜**、忌**
     */
    const REDIS_KEY_DETAIL_DAY = 'd_f_d_day_';

    /**
     * @var array 幸运色
     */
    protected $colors;

    /**
     * @var array 幸运方位
     */
    protected $directions;

    /**
     * @var array 幸运数字
     */
    protected $numbers;

    /**
     * @var array 幸运星座
     */
    protected $constellations;

    /**
     * @var array 运势指南类型icon_urls
     */
    protected $guide_icon_urls;

    public function initialize()
    {
        parent::initialize();

        $fortune_config = config('fortune');
        //幸运色
        $this->colors['gold_one'] = $fortune_config['gold_one'];
        $this->colors['gold_two'] = $fortune_config['gold_two'];
        $this->colors['gold_three'] = $fortune_config['gold_three'];
        $this->colors['wood_one'] = $fortune_config['wood_one'];
        $this->colors['wood_three'] = $fortune_config['wood_three'];
        $this->colors['water_one'] = $fortune_config['water_one'];
        $this->colors['water_two'] = $fortune_config['water_two'];
        $this->colors['water_three'] = $fortune_config['water_three'];
        $this->colors['fire_one'] = $fortune_config['fire_one'];
        $this->colors['fire_two'] = $fortune_config['fire_two'];
        $this->colors['fire_three'] = $fortune_config['fire_three'];
        $this->colors['soil_one'] = $fortune_config['soil_one'];
        $this->colors['soil_two'] = $fortune_config['soil_two'];
        $this->colors['soil_three'] = $fortune_config['soil_three'];


        //幸运方位
        $this->directions['east'] = $fortune_config['east'];
        $this->directions['south'] = $fortune_config['south'];
        $this->directions['west'] = $fortune_config['west'];
        $this->directions['north'] = $fortune_config['north'];
        $this->directions['southeast'] = $fortune_config['southeast'];
        $this->directions['northeast'] = $fortune_config['northeast'];
        $this->directions['southwest'] = $fortune_config['southwest'];
        $this->directions['northwest'] = $fortune_config['northwest'];

        //幸运数字
        $this->numbers['one'] = $fortune_config['one'];
        $this->numbers['two'] = $fortune_config['two'];
        $this->numbers['three'] = $fortune_config['three'];
        $this->numbers['four'] = $fortune_config['four'];
        $this->numbers['five'] = $fortune_config['five'];
        $this->numbers['six'] = $fortune_config['six'];
        $this->numbers['seven'] = $fortune_config['seven'];
        $this->numbers['eight'] = $fortune_config['eight'];
        $this->numbers['nine'] = $fortune_config['nine'];

        //幸运星座
        $this->constellations['aries'] = $fortune_config['aries'];
        $this->constellations['taurus'] = $fortune_config['taurus'];
        $this->constellations['gemini'] = $fortune_config['gemini'];
        $this->constellations['cancer'] = $fortune_config['cancer'];
        $this->constellations['leo'] = $fortune_config['leo'];
        $this->constellations['virgo'] = $fortune_config['virgo'];
        $this->constellations['libra'] = $fortune_config['libra'];
        $this->constellations['scorpio'] = $fortune_config['scorpio'];
        $this->constellations['sagittarius'] = $fortune_config['sagittarius'];
        $this->constellations['capricornus'] = $fortune_config['capricornus'];
        $this->constellations['aquarius'] = $fortune_config['aquarius'];
        $this->constellations['pisces'] = $fortune_config['pisces'];

        //运势指南icon_urls
        $this->guide_icon_urls['treasure'] = $fortune_config['treasure'];
        $this->guide_icon_urls['job'] = $fortune_config['job'];
        $this->guide_icon_urls['health'] = $fortune_config['health'];
        $this->guide_icon_urls['school'] = $fortune_config['school'];
        $this->guide_icon_urls['love'] = $fortune_config['love'];
        $this->guide_icon_urls['contact'] = $fortune_config['contact'];
        $this->guide_icon_urls['trip'] = $fortune_config['trip'];
        $this->guide_icon_urls['family'] = $fortune_config['family'];
        $this->guide_icon_urls['mood'] = $fortune_config['mood'];

    }

    /**
     * 获取首页 日运数据
     * @param $map
     * @return bool
     * @throws ApiException
     */
    public function getHomePageFortune($map)
    {
        $data = [];
        $time_now = $map['time'];
        $recode_info = $map['recode'];
        $dailyTime = strtotime(date('Y-m-d', $time_now) . ' 12:00:00');

        //从缓存获取数据
        $fortune_cache = $revive_day_cache = false;
        if ($this->cache_on >= 1)
        {
            $fortune_cache['lucky_name'] = Cache::get(self::REDIS_KEY_HOME_SUITABLE . $recode_info['id'] . '_' . $dailyTime);
            $fortune_cache['forbid_name'] = Cache::get(self::REDIS_KEY_HOME_AVOID . $recode_info['id'] . '_' . $dailyTime);
            $fortune_cache['tips'] = Cache::get(self::REDIS_KEY_ASTRO_TIP . $dailyTime);

            $revive_day_cache = Cache::get(self::REDIS_KEY_HOME_DAY . $recode_info['id'] . '_' . $dailyTime);
            if ($revive_day_cache)
                $fortune_cache['revive_day'] = $this->transReviveDayFromCacheToOriginal($revive_day_cache);
            $fortune_cache['sun_in_sign'] = Cache::get(self::REDIS_KEY_HOME_SUN_IN_SIGN . $recode_info['id']);

            $data = $fortune_cache;
        }
        if ($fortune_cache === false || $fortune_cache['lucky_name'] === false || $fortune_cache['forbid_name'] === false
            || $revive_day_cache === false || $fortune_cache['sun_in_sign'] === false || $fortune_cache['tips'] === false)
        {
            $dailyFortune = new FortuneIndex();
            $timeinfo = [
                'year' => date('Y', $dailyTime),
                'month' => date('m', $dailyTime),
                'day' => date('d', $dailyTime),
                'hour' => date('H', $dailyTime),
                'minute' => date('i', $dailyTime),
            ];
            $timeinfo['timezone'] = 8;
            $timeinfo['is_summer'] = isSummerTime($timeinfo['hour'], $timeinfo['minute'], 0,
                $timeinfo['month'], $timeinfo['day'], $timeinfo['year']) ? 1 : 0;

            if ($recode_info['month'] * 1 == $timeinfo['month'] * 1 && $recode_info['day'] * 1 == $timeinfo['day'] * 1) $dailyFortune->isBirth = true;

            $dailyFortune->astro = Astrolog::getInstance();
            $dailyFortune->astro
                ->setRecode1($recode_info)
                ->setAdvance($timeinfo)
                ->setExecPrefix(config('astrolog.prefix'))
                ->setIsAstrolabe(false)
                ->setUserSetting(config('astroset.setting1'))
                ->setGetDatas(['now', 'natal', 'transits', 'thirdprogressed'])
                ->getAstroDatas();

            $dailyFortune->nowData = $dailyFortune->astro->getDatas('now');
            $dailyFortune->natalData = $dailyFortune->astro->getDatas('natal');
            $dailyFortune->transitsData = $dailyFortune->astro->getDatas('transits');
            $dailyFortune->thirdprogressedData = $dailyFortune->astro->getDatas('thirdprogressed');
            $dailyFortune->active = $dailyFortune->getActive();
            $lucky_name = $dailyFortune->getSuitable($recode_info, $dailyTime, true);
            $forbid_name = $dailyFortune->getAvoid(true);
            $avoid = [];
            // 宜中出现过的，忌中不显示
            if (!empty($forbid_name)) foreach ($forbid_name as $avd) if (!in_array($avd, $lucky_name)) $avoid[] = $avd;
            if (empty($avoid)) $avoid[] = '百无禁忌';

            $revive_day = $dailyFortune->getTopic($recode_info, $dailyTime, true);

            $sun_in_sign = $dailyFortune->natalData['planets'][0]['in_sign_id'] ?? 1;// 如失败 则为白羊座
            // 获取今日天象
            $timeinfo['hour'] = 0;

            $dailyFortune->nowData = $dailyFortune->astro
                ->setAdvance($timeinfo)
                ->setGetDatas(['now'])
                ->getAstroDatas()
                ->getDatas('now');

            $tips = $dailyFortune->getNow();

            //赋值
            $data['lucky_name'] = $lucky_name;
            $data['forbid_name'] = $avoid;
            $data['revive_day'] = $revive_day;
            $data['sun_in_sign'] = $sun_in_sign;
            $data['tips'] = $tips;

            //写入缓存
            if ($this->cache_on >= 1)
            {
                Cache::set(self::REDIS_KEY_HOME_SUITABLE . $recode_info['id'] . '_' . $dailyTime, $lucky_name, self::CACHE_TIME);
                Cache::set(self::REDIS_KEY_HOME_AVOID . $recode_info['id'] . '_' . $dailyTime, $avoid, self::CACHE_TIME);
                Cache::set(self::REDIS_KEY_HOME_SUN_IN_SIGN . $recode_info['id'], $sun_in_sign, self::CACHE_TIME);
                Cache::set(self::REDIS_KEY_ASTRO_TIP . $dailyTime, $tips, self::CACHE_TIME);
                //存储**之日
                //把数据转换为缓存可用的数据
                $revive_day_cache = $this->transReviveDayFromOriginalToCache($revive_day);
                //写入缓存
                Cache::set(self::REDIS_KEY_HOME_DAY . $recode_info['id'] . '_' . $dailyTime, $revive_day_cache, self::CACHE_TIME);
            }

        }

        return $data;
    }

    /**
     * 获取日运详情页
     * @param $map
     * @return array|bool|mixed|Json
     * @throws ApiException
     */
    public function getDetailFortune($map)
    {
        $data = [];
        $map['time'] = strtotime(date('Y-m-d', $map['time']) . ' 12:00:00');
        //从缓存获取数据
        $fortune_cache = false;
        if ($this->cache_on >= 1)
        {
            //把缓存数据转化为可用的数据
            $other_cache = Cache::get(self::REDIS_KEY_DETAIL_DAY . $map['rid'] . '_' . $map['time']);
            if ($other_cache)
            {
                $fortune_cache = $this->transFromCacheToOriginal($other_cache);
                //获取 宜**（单独存储，因为首页也用到了）
                $fortune_cache['lucky_name'] = Cache::get(self::REDIS_KEY_DETAIL_SUITABLE . $map['rid'] . '_' . $map['time']);
                //获取 忌**（单独存储，因为首页也用到了）
                $fortune_cache['forbid_name'] = Cache::get(self::REDIS_KEY_DETAIL_AVOID . $map['rid'] . '_' . $map['time']);
                //获取 星象变动 名字（因为是写死的，不需要区分key）
                $fortune_cache['astro_name'] = Cache::get(self::REDIS_KEY_ASTRO_CHANGE_NAME);
                //获取 星象变动 图标（因为是写死的，不需要区分key）
                $fortune_cache['astro_icon_url'] = Cache::get(self::REDIS_KEY_ASTRO_CHANGE_ICON_URL);
                //获取 困难、警戒、平平、吉利、大吉 name和color（因为是写死的，不需要区分key）
                $fortune_cache['luck_adversity'] = Cache::get(self::REDIS_KEY_GRAPH_ICON_URL);
                $data = $fortune_cache;
            }
        }

        if ($fortune_cache === false || $fortune_cache['lucky_name'] == false || $fortune_cache['forbid_name'] == false || $fortune_cache['astro_name'] == false || $fortune_cache['astro_icon_url'] == false || $fortune_cache['luck_adversity'] == false)
        {
            $dailyFortune = new Index();
            $fortune_cache = $dailyFortune->init($map['rid'], $map['time']);
            $temp[] = $fortune_cache['fortune_list'][4];
            $temp[] = $fortune_cache['fortune_list'][3];
            $temp[] = $fortune_cache['fortune_list'][1];
            $temp[] = $fortune_cache['fortune_list'][0];
            $temp[] = $fortune_cache['fortune_list'][6];
            $temp[] = $fortune_cache['fortune_list'][2];
            $temp[] = $fortune_cache['fortune_list'][5];
            $temp[] = $fortune_cache['fortune_list'][7];
            $temp[] = $fortune_cache['fortune_list'][8];
            //婚恋/学习/事业/财富/出行/健康/交际/家人/心情
            $fortune_cache['fortune_list'] = $temp;

            $data = $fortune_cache;
            //写入缓存
            if ($this->cache_on >= 1)
            {
                //存储 宜**（单独存储，因为首页也用到了）
                Cache::set(self::REDIS_KEY_DETAIL_SUITABLE . $map['rid'] . '_' . $map['time'], $fortune_cache['lucky_name'], self::CACHE_TIME);
                //存储 忌**（单独存储，因为首页也用到了）
                Cache::set(self::REDIS_KEY_DETAIL_AVOID . $map['rid'] . '_' . $map['time'], $fortune_cache['forbid_name'], self::CACHE_TIME);
                //存储 星象变动 名字（因为是写死的，不需要区分key）
                Cache::set(self::REDIS_KEY_ASTRO_CHANGE_NAME, $fortune_cache['astro_name'], self::CACHE_TIME);
                //存储 星象变动 图标（因为是写死的，不需要区分key）
                Cache::set(self::REDIS_KEY_ASTRO_CHANGE_ICON_URL, $fortune_cache['astro_icon_url'], self::CACHE_TIME);
                //存储 困难、警戒、平平、吉利、大吉 name和color（因为是写死的，不需要区分key）
                Cache::set(self::REDIS_KEY_GRAPH_ICON_URL, $fortune_cache['luck_adversity'], self::CACHE_TIME);

                //把数据转换为缓存可用的数据
                $fortune_cache = $this->transFromOriginalToCache($fortune_cache);
                unset($fortune_cache['astro_name']);
                unset($fortune_cache['astro_icon_url']);
                unset($fortune_cache['lucky_name']);
                unset($fortune_cache['forbid_name']);
                unset($fortune_cache['luck_adversity']);
                //把剩余的内容写入缓存
                Cache::set(self::REDIS_KEY_DETAIL_DAY . $map['rid'] . '_' . $map['time'], $fortune_cache, self::CACHE_TIME);
            }
        }
        return $data;
    }

    /**
     * 把原始数据 转换为 缓存的数据
     * @param $fortune_cache
     * @return mixed
     */
    private function transFromOriginalToCache($fortune_cache)
    {
        $fortuneConfigs = config('fortune');
        //幸运色
        foreach ($this->colors as $k => $v)
        {
            if ($v == $fortune_cache['lucky_symbol'][0]['icon_url'])
            {
                $fortune_cache['lucky_symbol'][0]['icon_url'] = $k;
            }
        }

        //幸运方位
        foreach ($this->directions as $k => $v)
        {
            if ($v == $fortune_cache['lucky_symbol'][1]['icon_url'])
            {
                $fortune_cache['lucky_symbol'][1]['icon_url'] = $k;
            }
        }

        //幸运数字
        foreach ($this->numbers as $k => $v)
        {
            if ($v == $fortune_cache['lucky_symbol'][2]['icon_url'])
            {
                $fortune_cache['lucky_symbol'][2]['icon_url'] = $k;
            }
        }

        //幸运星座
        foreach ($this->constellations as $k => $v)
        {
            if ($v == $fortune_cache['lucky_symbol'][3]['icon_url'])
            {
                $fortune_cache['lucky_symbol'][3]['icon_url'] = $k;
            }
        }

        //转换某某之日列表
        foreach ($fortune_cache['revive_day'] as $k => $v)
        {
            $fortune_cache['revive_day'][$k] = $this->transReviveDayFromOriginalToCache($v);
        }

        //转换 几大方面的运势指南 列表
        foreach ($fortune_cache['fortune_advice'] as $k => $v)
        {
            $fortune_cache['fortune_advice'][$k] = $this->transAdivceFromOriginalToCache($v);
        }
        $fortuneAstroTips = $fortuneConfigs['astro_tips'];
        //转换 星象变动 列表
        foreach ($fortune_cache['astro_tips'] as $k => $v)
        {
            foreach ($fortuneAstroTips as $tips_k => $tips_v)
            {
                if ($tips_v === $v)
                {
                    $fortune_cache['astro_tips'][$k] = $tips_k;
                    break;
                }
            }
        }

        //转换 女神赠言（一条）
        foreach ($fortuneConfigs['word_tips'] as $k => $v)
        {
            if ($fortune_cache['goddess_list']['tips'] == $v['tips'])
            {
                $fortune_cache['goddess_list']['tips'] = $k;
                $fortune_cache['goddess_list']['from'] = $k;
                break;
            }
        }

        return $fortune_cache;

    }

    /**
     * 把缓存数据转换为返回给app的数据
     * @param $fortune_cache
     * @return mixed
     */
    private function transFromCacheToOriginal($fortune_cache)
    {
        $fortuneConfigs = config('fortune');
        //幸运色
        $color_icon_url = $fortune_cache['lucky_symbol'][0]['icon_url'];
        if (!empty($color_icon_url) && substr($color_icon_url, strlen($color_icon_url) - 3, 3) != 'png')
        {
            $fortune_cache['lucky_symbol'][0]['icon_url'] = $this->colors[$color_icon_url];
        }

        //幸运方位
        $color_direction_url = $fortune_cache['lucky_symbol'][1]['icon_url'];
        if (!empty($color_direction_url) && substr($color_direction_url, strlen($color_direction_url) - 3, 3) != 'png')
        {
            $fortune_cache['lucky_symbol'][1]['icon_url'] = $this->directions[$color_direction_url];
        }

        //幸运数字
        $color_number_url = $fortune_cache['lucky_symbol'][2]['icon_url'];
        if (!empty($color_number_url) && substr($color_number_url, strlen($color_number_url) - 3, 3) != 'png')
        {
            $fortune_cache['lucky_symbol'][2]['icon_url'] = $this->numbers[$color_number_url];
        }

        //幸运星座
        $color_constellation_url = $fortune_cache['lucky_symbol'][3]['icon_url'];
        if (!empty($color_constellation_url) && substr($color_constellation_url, strlen($color_constellation_url) - 3, 3) != 'png')
        {
            $fortune_cache['lucky_symbol'][3]['icon_url'] = $this->constellations[$color_constellation_url];
        }

        //转换某某之日列表
        foreach ($fortune_cache['revive_day'] as $k => $v)
        {
            $fortune_cache['revive_day'][$k] = $this->transReviveDayFromCacheToOriginal($v);
        }

        //转换 几大方面的运势指南 列表
        foreach ($fortune_cache['fortune_advice'] as $k => $v)
        {
            $fortune_cache['fortune_advice'][$k] = $this->transAdivceFromCacheToOriginal($v);
        }

        //转换 星象变动 列表
        foreach ($fortune_cache['astro_tips'] as $k => $v)
        {
            if (strlen($v) < 4)
            {
                $fortune_cache['astro_tips'][$k] = $fortuneConfigs['astro_tips'][$v];
            }
        }

        //转换 女神赠言（一条）
        if (strlen($fortune_cache['goddess_list']['tips']) < 4)
        {
            $fortune_cache['goddess_list'] = $fortuneConfigs['word_tips'][$fortune_cache['goddess_list']['tips']];
        }


        return $fortune_cache;
    }

    /**
     * 某某之日的原始数据转换为缓存数据
     * @param $revive_day
     * @return mixed
     */
    private function transReviveDayFromOriginalToCache($revive_day)
    {
        $fortuneConfigs = config('fortune');
        //**之日名字
        foreach ($fortuneConfigs['day'] as $k => $day)
        {
            if ($day === $revive_day['name'])
            {
                $revive_day['name'] = $k;
                break;
            }
        }
        //**之日描述
        foreach ($fortuneConfigs['day_des'] as $k => $day)
        {
            if ($day === $revive_day['tips'])
            {
                $revive_day['tips'] = $k;
                break;
            }
        }
        //**之日图标url
        foreach ($fortuneConfigs['icon_url'] as $k => $v)
        {
            if ($v === $revive_day['icon_url'])
            {
                $revive_day['icon_url'] = $k;
                break;
            }
        }
        //**之日弹出图标url
        foreach ($fortuneConfigs['tip_url'] as $k => $v)
        {
            if ($v === $revive_day['tips_url'])
            {
                $revive_day['tips_url'] = $k;
                break;
            }
        }

        return $revive_day;
    }

    /**
     * 某某之日的缓存数据转换为原始数据
     * @param $revive_day
     * @return mixed
     */
    private function transReviveDayFromCacheToOriginal($revive_day)
    {
        $fortuneConfigs = config('fortune');
        //**之日名字
        if (strlen($revive_day['name']) < 3)
        {
            $revive_day['name'] = $fortuneConfigs['day'][$revive_day['name']];
        }
        if (strlen($revive_day['tips']) < 3)
        {
            $revive_day['tips'] = $fortuneConfigs['day_des'][$revive_day['tips']];
        }
        if (substr($revive_day['icon_url'], strlen($revive_day['icon_url']) - 3, 3) != 'png')
        {
            $revive_day['icon_url'] = $fortuneConfigs['icon_url'][$revive_day['icon_url']];
        }
        if (substr($revive_day['tips_url'], strlen($revive_day['tips_url']) - 3, 3) != 'png')
        {
            $revive_day['tips_url'] = $fortuneConfigs['tip_url'][$revive_day['tips_url']];
        }

        return $revive_day;
    }

    /**
     * 单个运势指南 从原始数据 转换为 缓存数据
     * @param $fortune_advice
     * @return array
     */
    private function transAdivceFromOriginalToCache($fortune_advice)
    {
        $fortuneConfigs = config('fortune');

        foreach ($this->guide_icon_urls as $k => $v)
        {
            if ($v == $fortune_advice['icon_url'])
            {
                //转换icon_url
                $fortune_advice['icon_url'] = $k;
                //转换tips
                foreach ($fortuneConfigs['guide_tips_' . $k] as $guide_k => $guide_v)
                {
                    if ($guide_v == $fortune_advice['tips'])
                    {
                        $fortune_advice['tips'] = $guide_k;
                        break;
                    }
                }
            }
        }
        return $fortune_advice;
    }

    /**
     * 把运势指南 cache转换为原始数据
     * @param $fortune_advice
     * @return array
     */
    private function transAdivceFromCacheToOriginal($fortune_advice)
    {
        //转换词条
        if (strlen($fortune_advice['tips']) < 4)
        {
            $fortune_advice['tips'] = config('fortune.guide_tips_' . $fortune_advice['icon_url'])[$fortune_advice['tips']];
        }
        //转换图标
        if (substr($fortune_advice['icon_url'], strlen($fortune_advice['icon_url']) - 3, 3) != 'png')
        {
            $fortune_advice['icon_url'] = $this->guide_icon_urls[$fortune_advice['icon_url']];
        }
        return $fortune_advice;
    }


    /**
     * 获取日运首页信息
     * @param int $uid
     * @param int $time
     * @param int $rid
     * @param bool $activeTime
     * @param int $dayFortuneVersion 日运版本 1=>旧版本 2=>2.4.1厄运消除及以后版本
     * @return array|bool|mixed|Json
     * @throws ApiException
     */
    public function getIndexInfo($uid = 0, $time = 0, $rid = 0, $activeTime = false, $dayFortuneVersion = 1)
    {
        $header = request()->header();
        $arr = \app\common\cachemodel\FortuneCache::CheckFortuneSevenUnlockStatus($uid, $rid, $time);
        //旧缓存
//        $arr = (new Fortune())->getUserUnlockFortune(['uid' => $uid, 'time' => $time, 'rid' => $rid]);

        $is_unlock = $arr['is_unlock'];
        $seven = $arr['time'];//日记标识
//        $seven = $arr['seven'];//日记标识
        $fortune = $arr['fortune'];//七天解锁标识
        $selfId = $arr['selfId'];
        $note_status = $arr['note_status'];

        if ($is_unlock === true)
        {

            $is_use_cache = 1;
            if ($is_use_cache)
            {
                $map = ['time' => $time, 'rid' => $rid, 'uid' => $uid];
                // $data = (new FortuneCache())->getDetailFortune($map);
                $data = (new \app\common\cachemodel\FortuneCache())->getDayFortune($map, $dayFortuneVersion);
                $data['time'] = $seven;
                $data['fortune'] = $fortune;
            } else
            {
                $dailyFortune = new Index();
                $dailyFortune->dayFortuneVersion = $dayFortuneVersion;
                $data = $dailyFortune->init($rid, strtotime(date('Y-m-d', $time) . ' 12:00:00'));
                $data['time'] = $seven;
                $data['fortune'][] = $fortune;
                $temp[] = $data['fortune_list'][4];
                $temp[] = $data['fortune_list'][3];
                $temp[] = $data['fortune_list'][1];
                $temp[] = $data['fortune_list'][0];
                $temp[] = $data['fortune_list'][6];
                $temp[] = $data['fortune_list'][2];
                $temp[] = $data['fortune_list'][5];
                $temp[] = $data['fortune_list'][7];
                $temp[] = $data['fortune_list'][8];
                //婚恋/学习/事业/财富/出行/健康/交际/家人/心情
                $data['fortune_list'] = $temp;
            }

        }


        // 活动开关，默认关闭
        $config = config('active.fortune_active');
        $data['active_switch'] = [
            'day_active' => [
                'is_open' => false,
                'icon' => '',
                'banner' => '',
                'target' => 'link',
                'link' => Env::get('host.domain') . '/web/fortune_year/active_details',//大礼包h5
            ],
            'month_active' => [
                'is_open' => false,
                'icon' => '',
                'banner' => $config['banner'],
                'target' => 'link',
                'link' => Env::get('host.domain') . '/web/fortune_year/active_details',//大礼包h5
            ],
            'year_active' => [
                'is_open' => false,
                'icon' => $config['icon'],
                'banner' => $config['banner'],
                'target' => 'link',
                'link' => Env::get('host.domain') . '/web/fortune_year/active_details',//大礼包h5
            ],

        ];

        //若在活动时间内，开启
        if ($activeTime)
        {
            $data['active_switch']['day_active']['is_open'] = false;
            $data['active_switch']['month_active']['is_open'] = true;
            $data['active_switch']['year_active']['is_open'] = true;
        }

        // 去重
        $seven = array_unique($seven);
        // 重新索引
        $data['time'] = array_values($seven);

        // 去重
        $fortune = array_unique($fortune);
        // 重新索引
        $data['fortune'] = array_values($fortune);
        $data['self_rid'] = $selfId['id'] ?? 0;
        $data['note_status'] = $note_status;

        return $data;
    }

    /**
     * APP 2.10.5 版本
     * 获取日运首页信息
     * @param int $uid
     * @param int $time
     * @param int $rid
     * @param bool $activeTime
     * @param int $dayFortuneVersion 日运版本 1=>旧版本 2=>2.4.1厄运消除及以后版本
     * @return array|bool|mixed|Json
     * @throws ApiException
     */
    public function getIndexInfoV2($uid = 0, $time = 0, $rid = 0, $activeTime = false, $dayFortuneVersion = 1, int $vipExpireTime = 0)
    {
        $arr = \app\common\cachemodel\FortuneCache::CheckFortuneSevenUnlockStatus($uid, $rid, $time, $vipExpireTime);

        $is_unlock = $arr['is_unlock'];
        $seven = $arr['time'];//日记标识
        $fortune = $arr['fortune'];//七天解锁标识
        $selfId = $arr['selfId'];
        $note_status = $arr['note_status'];

        if ($is_unlock === true)
        {

            $is_use_cache = 1;
            if ($is_use_cache)
            {
                $map = ['time' => $time, 'rid' => $rid, 'uid' => $uid];
                // $data = (new FortuneCache())->getDetailFortune($map);
                $data = (new \app\common\cachemodel\FortuneCache())->getDayFortune($map, $dayFortuneVersion);
                $data['time'] = $seven;
                $data['fortune'] = $fortune;
            } else
            {
                $dailyFortune = new Index();
                $dailyFortune->dayFortuneVersion = $dayFortuneVersion;
                $data = $dailyFortune->init($rid, strtotime(date('Y-m-d', $time) . ' 12:00:00'));
                $data['time'] = $seven;
                $data['fortune'][] = $fortune;
                $temp[] = $data['fortune_list'][4];
                $temp[] = $data['fortune_list'][3];
                $temp[] = $data['fortune_list'][1];
                $temp[] = $data['fortune_list'][0];
                $temp[] = $data['fortune_list'][6];
                $temp[] = $data['fortune_list'][2];
                $temp[] = $data['fortune_list'][5];
                $temp[] = $data['fortune_list'][7];
                $temp[] = $data['fortune_list'][8];
                //婚恋/学习/事业/财富/出行/健康/交际/家人/心情
                $data['fortune_list'] = $temp;
            }
        }

        // 活动开关，默认关闭
        $config = config('active.fortune_active');
        $data['active_switch'] = [
            'day_active' => [
                'is_open' => false,
                'icon' => '',
                'banner' => '',
                'target' => 'link',
                'link' => Env::get('host.domain') . '/web/fortune_year/active_details',//大礼包h5
            ],
            'month_active' => [
                'is_open' => false,
                'icon' => '',
                'banner' => $config['banner'],
                'target' => 'link',
                'link' => Env::get('host.domain') . '/web/fortune_year/active_details',//大礼包h5
            ],
            'year_active' => [
                'is_open' => false,
                'icon' => $config['icon'],
                'banner' => $config['banner'],
                'target' => 'link',
                'link' => Env::get('host.domain') . '/web/fortune_year/active_details',//大礼包h5
            ],

        ];

        //若在活动时间内，开启
        if ($activeTime)
        {
            $data['active_switch']['day_active']['is_open'] = false;
            $data['active_switch']['month_active']['is_open'] = true;
            $data['active_switch']['year_active']['is_open'] = true;
        }

        // 去重
        $seven = array_unique($seven);
        // 重新索引
        $data['time'] = array_values($seven);
        // 去重
        $fortune = array_merge($fortune, $arr['vip_time']);
        $fortune = array_unique($fortune);
        // 重新索引
        $data['fortune'] = array_values($fortune);
        $data['self_rid'] = $selfId['id'] ?? 0;
        $data['note_status'] = $note_status;

        return $data;
    }

    /**
     * 获取日运历史
     * @param int $uid
     * @param int $type // 1=>日记解锁 2=>订单解锁
     * @param string $day
     * @param int $rid
     * @param string $unlockId
     * @return array|bool|mixed|string|Json
     * @throws ApiException
     */
    public function getHistoryDayFortuneInfo($uid = 0, int $type, $day = '', $rid = 0, string $unlockId)
    {
        $recodeInfo = null;
        if ($type === 1)
        {   // 日记解锁
            $NoteInfo = (new \app\common\cachemodel\FortuneNote())->getInfoById($unlockId);
            $rid = $NoteInfo['rid'];
            $recodeInfo = (new \app\common\cachemodel\Recode())->getInfoById($rid);
            if ($recodeInfo['uid'] != $uid)
            {
                throw new ApiException('服务异常！请稍后再试～', 200, 0);
            }
            $time = (int)$NoteInfo['time'];
            $fortuneOrderTime = [date('Y-n-j', $NoteInfo['time'])];
        } else
        {   // 订单解锁
            $orders = (new \app\common\cachemodel\Orders())->batchGetInfoByIds($unlockId);
            if (!$orders || $orders[$unlockId]['uid'] != $uid)
            {
                throw new ApiException('订单不存在', 200, 0);
            }
            $orders = (new OrdersLib())->getOrderDetails($orders);
            $fortune = array_column($orders, 'fortune_data');
            $fortuneOrderTime = prDates(['start' => $fortune[0][0]['start_time'], 'end' => $fortune[0][0]['end_time'], 'type' => 1]); //1=>日 2=>月 3=>年
            $rids = explode(',', $fortune[0][0]['rid']);
            if (!in_array($rid, $rids, false))
            {
                throw new ApiException('服务异常！请稍后再试～', 200, 0);
            }
            if (empty($day) || !in_array($day, $fortuneOrderTime, true))
            {
                $day = $fortuneOrderTime[0];
            }
            $time = strtotime($day);
        }

        $is_use_cache = 1;
        if ($is_use_cache)
        {
            $map = ['time' => $time, 'rid' => $rid, 'uid' => $uid];
            $data = (new \app\common\cachemodel\FortuneCache())->getDayFortune($map, 2);
            $data['fortune'] = $fortuneOrderTime;
        } else
        {
            $dailyFortune = new Index();
            $data = $dailyFortune->init($rid, strtotime(date('Y-m-d', $time) . ' 12:00:00'));
            $data['fortune'][] = $fortuneOrderTime;
            $temp[] = $data['fortune_list'][4];
            $temp[] = $data['fortune_list'][3];
            $temp[] = $data['fortune_list'][1];
            $temp[] = $data['fortune_list'][0];
            $temp[] = $data['fortune_list'][6];
            $temp[] = $data['fortune_list'][2];
            $temp[] = $data['fortune_list'][5];
            $temp[] = $data['fortune_list'][7];
            $temp[] = $data['fortune_list'][8];
            //婚恋/学习/事业/财富/出行/健康/交际/家人/心情
            $data['fortune_list'] = $temp;
        }

        if ($type === 2)
        {
            // 当获取日运解锁数据时
            $noteData = (new FortuneNote())->getUserNote(['uid' => $uid]);
            if ($noteData)
            {
                $noteTime = array_column($noteData, 'time');
                $noteTime = array_map(function ($timeValue)
                {
                    return date('Y-n-j', $timeValue);
                }, $noteTime);

                $data['time'] = array_values(array_intersect($noteTime, $fortuneOrderTime));

            } else
            {
                $data['time'] = [];
            }
            $data['note_status'] = in_array($day, $data['time'], true) ? 1 : 0;

        } else
        {
            $data['time'] = $fortuneOrderTime;
            $data['note_status'] = 1;

            $unlockRecodeInfo = (new Util)->getFortuneDetailRecodeInfo([$recodeInfo]);
            $data['unlock_recode_info'] = ['info' => $unlockRecodeInfo];
        }

        return $data;
    }

    /**
     * 获取当前月份的运势日历数据
     * @param int $rid
     * @param int $time
     * @param int $uid
     * @return array
     * @throws ApiException
     * @throws Exception
     */
    public function getFortuneCalendar($rid = 0, $time = 0, $uid = 0, int $vipExpireTime = 0)
    {
        $unlock_Data = \app\common\cachemodel\FortuneCache::CheckFortuneMonthUnlockStatus($uid, $rid, $time, $vipExpireTime);
        // 去重
        $fortune = array_merge($unlock_Data['fortune'], $unlock_Data['vip_time']);
        $fortune = array_unique($fortune);

        $arr['fortune'] = array_values($fortune);//解锁标识
        $arr['time'] = $unlock_Data['time'];//日记标识
        //旧缓存

//        // 返回值初始化
//        $arr = [
//            'time' => [],
//            'fortune' => [],
//        ];
//
//        $AwardUserModel = new AwardUser();
//        $RecodeModel = new  Recode();
//        $FortuneNoteModel = new FortuneNote();
//        $Orders = new Orders();
//
//        // 获取日记标识
//        $times = $FortuneNoteModel->getRidNote(['rid' => $rid]);
//
//        // 是否有日记的日期
//        foreach ($times as $k => $v)
//        {
//            $date = strtotime(date('Y-m', $v['time']));
//
//            if ($time == $date)
//            {
//                $arr['time'][] = date('d', $v['time']);
//            }
//        }
//
//        // 查询当前用户是否为VIP 或 vip2
////        $unlock_users = Util::getVips($uid);
//        $unlock_users = false;
//
//        // 获取当前用户的档案id
//        $selfId = $RecodeModel->getSelfRecode(['uid' => $uid]);
//
//        if ($unlock_users === 1 || ($unlock_users > 1 && $rid == $selfId['id']))
//        {
//
//            for ($i = $time; $i < strtotime('+1 month', $time); $i += 86400)
//            {
//                $arr['fortune'][] = date('d', $i);
//            }
//        }// 非VIP 查询购买的订单 和  是否有赠送的 当月所有日期
//        else
//        {
//            // 2018年年底活动  最后七天免费永久解锁
//            if (date('Y-m', $time) == '2018-12' && $rid == $selfId['id'])
//            {
//                $arr['fortune'][] = "25";
//                $arr['fortune'][] = "26";
//                $arr['fortune'][] = "27";
//                $arr['fortune'][] = "28";
//                $arr['fortune'][] = "29";
//                $arr['fortune'][] = "30";
//                $arr['fortune'][] = "31";
//            }
//
//            //2019五一活动期间免费查看
////            if (checktime() && date('Y-m', $time) == '2019-05' && $rid == $selfId['id']) {
////                $arr['fortune'][] = "01";
////                $arr['fortune'][] = "02";
////                $arr['fortune'][] = "03";
////                $arr['fortune'][] = "04";
////            }
//
//            // 获取档案购买的日运订单
//            $fortuneOrders = $Orders->fortune_orders(['uid' => $uid, 'rid' => $rid, 'type' => 1]);
//
//            $arr1 = [];
//
//            $arr2 = [];
//
//            //获取当前月份 总共有多少天
//            $month = month_days($time);
//
//            if (!empty($fortuneOrders))
//            {
//                foreach ($fortuneOrders as $k => $v)
//                {
//                    if (in_array($rid, explode(',', $v['rids'])))
//                    {
//                        $extime = json_decode($v['extend'], true)['expire_time'];
//
//                        if (isset($extime) || !empty($extime))
//                        {
//                            $v['expire_time'] = $extime;
//                        }
//                        $date = strtotime(date('Y-m', $v['time']));
//
//                        $end_time = strtotime('-1 days', strtotime($v['expire_time'], $v['time']));
//
//                        if (in_array($v['gid'], [3, 4, 5, 6]))
//                        {
//                            if (($time >= $date) && $time <= $end_time)
//                            {
//                                $order_start_time = strtotime(date('Y-m-d', $v['time']));
//                                $order_end_time = strtotime(date('Y-m-d', $end_time));
//                                // 遍历当前月份的具体日期
//                                foreach ($month as $kk => $vv)
//                                {
//                                    if ($order_start_time <= $vv && $vv <= $order_end_time)
//                                    {
//                                        $arr1[] = date('d', $vv);
//                                    }
//                                }
//                            };
//                        } elseif ($v['gid'] == 2)
//                        {
//                            if ($time == $date)
//                            {
//                                $arr1[] = date('d', $v['time']);
//                                $extime = json_decode($v['extend'], true)['expire_time'];
//                                if (isset($extime) || !empty($extime))
//                                {
//                                    $arr1[] = date('d', strtotime('+1day', $v['time']));
//                                }
//                            }
//                        }
//                    }
//
//                }
//            }
////        获取中奖纪录
//            $prize = $AwardUserModel->get_award_fortune(['uid' => $uid, 'rid' => $rid, 'type' => 1, 'self_id' => $selfId]);
//
//
//            if (!empty($prize))
//            {
//                //  遍历所有获赠的日运
//                foreach ($prize as $k => $v)
//                {
//                    $extend = json_decode($v['extend'], true);
//                    // 获赠的日运的开始时间 时间戳
//                    $date = strtotime(date('Y-m', $extend['award_time']));
//                    // 获赠的日运的结束时间
//                    $end_time = strtotime('-1 days', strtotime($v['expire_time'], $extend['award_time']));
//
//                    // 获取赠送的日运记录
//                    if (in_array($v['aid'], [3, 4, 5, 6]))
//                    {
//                        //判断当前查看的月份是否在赠送的范围内
//                        if (($time >= $date) && $time <= $end_time)
//                        {
//                            $extend_start_time = strtotime(date('Y-m-d', $extend['award_time']));
//                            $extend_end_time = strtotime(date('Y-m-d', $end_time));
//                            // 遍历当前月份的具体日期
//                            foreach ($month as $kk => $vv)
//                            {
//                                // 判断获赠的具体日期是否在当前月具体日期内
//                                if ($extend_start_time <= $vv && $vv <= $extend_end_time)
//                                {
//                                    $arr2[] = date('d', $vv);
//                                }
//                            }
//                        }
//
//                    } // 获取赠送一日的日运记录
//                    elseif ($v['aid'] == 2)
//                    {
//                        // 当前查看的具体日期是否和赠送的具体日期一样
//                        if ($time == $date)
//                        {
//                            $arr2[] = date('d', $extend['award_time']);
//                        }
//                    }
//                }
//            }
//            // 合并活动的日期，订单购买的日期，后台赠送的日期
//            $arr['fortune'] = array_merge($arr['fortune'], $arr1, $arr2);
//            if (date('Y-m', $time) == date('Y-m', time()))
//            {
//                $arr['fortune'][] = date('d', time());
//            }
//            // 去重
//            $arr['fortune'] = array_unique($arr['fortune']);
//            // 重新索引
//            $arr['fortune'] = array_values($arr['fortune']);
//            $arr['time'] = array_unique($arr['time']);
//            // 重新索引
//            $arr['time'] = array_values($arr['time']);
//        }
        return $arr;
    }


    /**
     * 获取运势商品信息
     * @param $is_apple_pay
     * @param $apple_goods
     * @return array|Json
     */
    public function getFortuneGoods($is_apple_pay, $apple_goods)
    {
        $month_start = config('fortune.fortune_time_range')['month']['start'];
        $month_end = config('fortune.fortune_time_range')['month']['end'];
        $year_start = config('fortune.fortune_time_range')['year']['start'];
        $year_end = config('fortune.fortune_time_range')['year']['end'];

        $good_model = new Goods();

        $fortune_day_goods = $good_model->getGoodsForDay(['id' => 2]);
        $fortune_month_goods = $good_model->getGoodsForMonth(['id' => 20]);
        $fortune_year_goods = $good_model->getGoodsForYear(['id' => 24]);
        if (($fortune_day_goods || $fortune_month_goods || $fortune_year_goods) === false)
        {
            return show(config('code.error'), $good_model->getError());
        }

        //若当前请求是ios且在配置版本内,就显示配置的商品信息
        if ($is_apple_pay)
        {
            $fortune_day_goods = $apple_goods['fortune_day_goods'];
            $fortune_month_goods = $apple_goods['fortune_month_goods'];
            $fortune_year_goods = $apple_goods['fortune_year_goods'];
        }
        $day_goods = [];
        $month_goods = [];
        $year_goods = [];
//        $des = '520,全场七折!';
        foreach ($fortune_day_goods as $v)
        {
//            if ($activeSwitch) {
//                $v['now_prize'] = floatval($v['now_prize'] * 0.7);
//                $v['goods_des'] = $des;
//            }

            $activeDiscount = active($v['id']);
            if ($activeDiscount['discount'] && !$is_apple_pay)
            {
                $v['now_prize'] *= $activeDiscount['discount'];
            }

            $day_goods[] = [
                'gid' => $v['id'],
                'name' => $v['name'],
                'or_price' => sprintf("%.2f", $v['or_prize']),
                'now_price' => sprintf("%.2f", $v['now_prize']),
                'goods_des' => $v['goods_des'],
            ];
        }
        foreach ($fortune_month_goods as $v)
        {
            $activeDiscount = active($v['id']);
            if ($activeDiscount['discount'] && !$is_apple_pay)
            {
                $v['now_prize'] *= $activeDiscount['discount'];
            }
            $month_goods[] = [
                'gid' => $v['id'],
                'name' => $v['name'],
                'or_price' => sprintf("%.2f", $v['or_prize']),
                'now_price' => sprintf("%.2f", $v['now_prize']),
                'goods_des' => $v['goods_des'],
            ];
        }
        foreach ($fortune_year_goods as $v)
        {
            $activeDiscount = active($v['id']);
            if ($activeDiscount['discount'] && !$is_apple_pay)
            {
                $v['now_prize'] *= $activeDiscount['discount'];
            }
            $year_goods[] = [
                'gid' => $v['id'],
                'name' => $v['name'],
                'or_price' => sprintf("%.2f", $v['or_prize']),
                'now_price' => sprintf("%.2f", $v['now_prize']),
                'goods_des' => $v['goods_des'],
            ];
        }

        $data = [
            'fortune_day' => [
                'goods_data' => $day_goods,
            ],
            'fortune_month' => [
                'goods_data' => $month_goods,
                'time_range' => [
                    'start_time' => $month_start,
                    'end_time' => $month_end,
                ],
            ],
            'fortune_year' => [
                'goods_data' => $year_goods,
                'time_range' => [
                    'start_time' => $year_start,
                    'end_time' => $year_end,
                ],
            ],
        ];
        return $data;
    }

}
